<script>
	import Vue from 'vue';
	export default {
		onLaunch: function() {
			this.$store.commit("initApp");
			uni.getSystemInfo({
				success: function(e) {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45
					}
					// #endif
					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight
					let custom = wx.getMenuButtonBoundingClientRect()
					Vue.prototype.Custom = custom
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight
					// #endif
					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight
					// #endif
					let unitRatio = 750 / uni.getSystemInfoSync().windowWidth
					Vue.prototype.StatusBarRpx = Vue.prototype.StatusBar * unitRatio
					Vue.prototype.CustomBarRpx = Vue.prototype.CustomBar * unitRatio
					Vue.prototype.unitRatio = unitRatio
					Vue.mixin({
						data() {
							return {
								StatusBar: Vue.prototype.StatusBar, //状态栏高度(px)
								CustomBar: Vue.prototype.CustomBar, //整个标题栏高度(px)
								StatusBarRpx: Vue.prototype.StatusBarRpx, //状态栏高度(rpx)
								CustomBarRpx: Vue.prototype.CustomBarRpx, //整个标题栏高度(rpx)
							}
						},
					})
				},
			})
			// #ifdef APP-PLUS
			// 锁定屏幕显示方向为竖屏正方向
			plus.screen.lockOrientation('portrait-primary');
			// 推送服务
			// plus.push.addEventListener('click', () => {
			// 	plus.nativeUI.toast('提示消息');
			// 	this.pushCallback(message);
			// });
			// plus.push.addEventListener('receive', () => {
			// 	plus.nativeUI.toast('透传消息');
			// 	this.pushCallback(message);
			// });
			// 加载本地字体
			// uni.loadFontFace({
			// 	family: 'pingfang',
			// 	source: `url(${plus.io.convertLocalFileSystemURL('_www/static/font/pingfang.ttf')})`,
			// })
			// #endif
			// global.token && this.$store.dispatch('getCartList');

			//  聊天模块
			// const WS_HOST = 'wss://www.goldenbeartalent.com:8311'
			// uni.onTabBarMidButtonTap(() => {
			// 	this.$urouter.navigateTo('/pages/global_pop/publish/index')
			// })

			// uni.$on('appLoginSuccess', (res) => {
			// 	uni.closeSocket()
			// 	this.initializeSocket()
			// })
			// uni.setStorageSync('chatOne', '')
		},
		onShow: function() {
			console.log('APP Show');
			// #ifdef APP-PLUS
			// 获取参数
			const args = plus.runtime.arguments;
			if (args) {
				let params_str = args.split('?')[1];
				if (params_str) {
					let params = params_str.split('&').reduce(function(total, item) {
						let arr = item.split('=');
						total[arr[0]] = arr[1];
						return total;
					}, {});
					console.log(params);
					// params 参数: path 跳转路径 options 参数
					uni.navigateTo({
						url: `${params.path}?goods_id=${params.goods_id}&activity_id=${params.activity_id}&sku_id=${params.sku_id}&bargain_id=${params.bargain_id}`
					})
				}
			}
			// 快捷入口
			// this.init3DTouch();
			// #endif
			// 聊天
			// uni.closeSocket()
			// this.initializeSocket();

			// 小程序自动更新
			if (uni.canIUse('getUpdateManager')) {
				//判断当前微信版本是否支持版本更新
				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate(function(res) {
					if (res.hasUpdate) {
						// 请求完新版本信息的回调
						updateManager.onUpdateReady(function() {
							uni.showModal({
								title: '更新提示',
								content: '新版本已经准备好，是否重启应用？',
								success: function(res) {
									if (res.confirm) {
										// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
										updateManager.applyUpdate();
									}
								},
							});
						});
						updateManager.onUpdateFailed(function() {
							uni.showModal({
								// 新的版本下载失败
								title: '已经有新版本了哟~',
								content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
							});
						});
					} else {}
				});
			} else {
				uni.showModal({
					// 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
					title: '提示',
					content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
				});
			}
		},
		onHide: function() {
			// 用户退出app时，把二次验证状态改为true
			console.log('APP Hide');
			uni.$emit('APP_HIDE', {
				msg: 'app hide'
			})
			global.appointDate = '';
			global.typeId = '';
		},
		methods: {
			// 推送回调
			pushCallback(message) {
				console.log("to do list", message);
			},

			initializeSocket() {
				// console.log(WS_HOST)
				if (global.token) {
					// 链接socket
					uni.connectSocket({
						url: 'wss://www.goldenbeartalent.com:8311'
					});
					// 接收socket消息
					uni.onSocketOpen(res => {
						console.log(res)
						console.log('socket已连接')
						uni.sendSocketMessage({
							data: JSON.stringify({
								type: 'bind',
								uid: global.userInfo.id
							})
						})
						uni.onSocketMessage(onMessage => {
							console.log('111', onMessage)
							// let onMessageJson =onMessage.data;
							let onMessageJson = JSON.parse(onMessage.data);
							// console.log(onMessageJson)
							// chat_type 7 解散群聊 8 系统消息 9 监听有新的好友申请  10 入群验证
							// if(onMessageJson.msg_type == 8) return  console.log("系统消息");
							// if (onMessageJson.content == "群主解散了群") {
							// 	uni.$emit("upDataList")
							// }
							// if (onMessageJson.chat_type == 10) return this.postJoinList();
							// if (onMessageJson.chat_type == 9) return this.postApplyData();
							// return
							if (onMessageJson.type == 'signIn') return this.upLoadClientID(onMessageJson.clientID);
							// if (onMessageJson.msg_type == 4 || onMessageJson.msg_type == 5) {
							// 	onMessageJson.content = JSON.parse(onMessageJson.content);
							// }
							// this.addHistory(onMessageJson);
							// const top = 99999;
							console.log('触发')
							setTimeout(() => {
								uni.$emit("newMsg", {
									onMessageJson
								});
							})
							// uni.$emit("updateMessage");
							// switch (onMessageJson.class) {
							//   case 'say':
							//     // this.$store.commit('messageReceived', onMessageJson)
							//     break;
							//   case 'init':
							//     // 发送握手消息
							//     uni.sendSocketMessage({
							//       data: JSON.stringify({
							//         class: 'init',
							//         from_id: global.userInfo.id
							//       })
							//     })
							//     break;
							//   default:
							//     // statements_def
							//     break;
							// }

						})

						// uni.sendSocketMessage({
						//   data: JSON.stringify({ c: 'Message', a: 'ping' })
						// });



						// 定时发送心跳消息避免断开
						setInterval(() => {
							uni.sendSocketMessage({
								data: JSON.stringify({
									class: 'ping'
								})
							});
						}, 25000)

						// socket 断开链接后尝试重新链接
						uni.onSocketError(err => {
							console.log(err)
							this.initializeSocket()
						})
					});
					// uni.onSocketError(function (res) {
					//   console.log('WebSocket连接打开失败，请检查！');
					// });
				}
			},
			// 上传更新clientID
			upLoadClientID(clientID) {
				console.log(clientID);
				this.$api.post(global.apiUrls.updateclientID, {
						client_id: clientID
					})
					.then(res => {
						// console.log(res)
						if (res.data.code == 1) {

						}
					})
					.catch(err => {
						// this.$popup.showToast('保存失败')
					})
			},
			// #ifdef APP-PLUS
			// 权限检查
			checkPermissions() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') { // 判断是Android
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					// 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
					if (!areNotificationsEnabled) {
						uni.showModal({
							title: '通知权限开启提醒',
							content: '您还没有开启通知权限，无法接受到消息通知，是否前往设置？',
							success: function(res) {
								if (res.confirm) {
									var Intent = plus.android.importClass('android.content.Intent');
									var Build = plus.android.importClass("android.os.Build");
									//android 8.0引导
									if (Build.VERSION.SDK_INT >= 26) {
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
										intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
									} else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0
										var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
										intent.putExtra("app_package", pkName);
										intent.putExtra("app_uid", uid);
									} else { //(<21)其他--跳转到该应用管理的详情页
										intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
										var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
										intent.setData(uri);
									}
									// 跳转到该应用的系统通知设置页
									main.startActivity(intent);
								}
							}
						});
					}
				} else if (plus.os.name == 'iOS') { // 判断是ISO
					var isOn = undefined;
					var types = 0;
					var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
					if (settings) {
						types = settings.plusGetAttribute('types');
						plus.ios.deleteObject(settings);
					} else {
						types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
					}
					plus.ios.deleteObject(app);
					isOn = (0 != types);
					if (isOn == false) {
						uni.showModal({
							title: '通知权限开启提醒',
							content: '您还没有开启通知权限，无法接受到消息通知，是否前往设置？',
							success: function(res) {
								if (res.confirm) {
									var app = plus.ios.invoke('UIApplication', 'sharedApplication');
									var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
									plus.ios.invoke(app, 'openURL:', setting);
									plus.ios.deleteObject(setting);
									plus.ios.deleteObject(app);
								}
							}
						});
					}
				}
				// #endif
			},
			// 初始化 3D Touch
			init3DTouch() {
				this.$api.post(global.apiUrls.postHomeGrid, {
					typeid: 2
				}).then(res => {
					if (res.data.code == 1) {
						let list = res.data.data;
						const dcRichAlert = uni.requireNativePlugin('DCloud-RichAlert');
						if (dcRichAlert) {
							let _shortcut = '[';
							let len = list.length;
							list.forEach((item, index) => {
								_shortcut +=
									`{"id":"${item.href}","describe":"${item.name}","icon":"${item.thumb}","shortlabel":"${item.name}","longlabel":"${item.name}"}`;
								if ((index + 1) != len) {
									_shortcut += ','
								}
							})
							_shortcut += ']';
							dcRichAlert.show({
								shortcut: _shortcut
							}, result => {
								if (result.post === 'success') {
									uni.navigateTo({
										url: result.id
									})
								}
							});
						}
					}
				});
			}
			// #endif
		}
	}
</script>

<style lang="scss">
	/* #ifndef APP-PLUS-NVUE */
	
	/* @import "uview-ui/index.scss"; */
	@import "uview-ui/index.scss";
	@import "./style/icon.css";
	@import "./style/main.css";
	@import "./style/animation.css";
	@import "./style/iconfont.css";

	/* #endif */
	/* 推广 */
	.statisticsBgColor {
		background: #f94032;
		color: #FFFFFF;
	}
</style>
